<?php
class UserController extends BaseController
{

        private $userDao;
        public function __construct(UserDao $userDao)
        {
                $this->userDao = $userDao;
        }
        public function users()
        {
                $data = $this->userDao->getUsersAll();
                $this->sendOutput(json_encode($data, true));
        }

        public function getUserById($id)
        {
                // 判断是否是字符串，如果是，转换成数字
                if (is_string($id)) {
                        $id = intval($id);
                }
                $data = $this->userDao->getUserById($id);
                $this->sendOutput(json_encode($data, true));
        }
        public function addUser()
        {
                if (empty($_POST) && false !== strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
                        $content = file_get_contents('php://input');
                        $post = (array) json_decode($content, true);
                } else {
                        $post = $_POST;
                }
                if (!isset($post['username']) || !isset($post['password']) || !isset($post['email'])) {
                        throw new InvalidArgumentException("username, password, email are required");
                }
                $username = $post['username'];
                $password = $post['password'];
                $email = $post['email'];
                $password = password_hash($password, PASSWORD_BCRYPT);
                $role = $post['role'] ?? "user";
                error_log("username: $username, password: $password, email: $email, role: $role");
                $this->userDao->addUser($username, $password, $email, $role);
                $this->success();
        }
        public function listAction()
        {
                $strErrorDesc = '';
                $requestMethod = $_SERVER["REQUEST_METHOD"];
                $arrQueryStringParams = $this->getQueryStringParams();

                if (strtoupper($requestMethod) == 'GET') {
                        try {
                                $userDao = new UserDao();

                                $intLimit = 10;
                                if (isset($arrQueryStringParams['limit']) && $arrQueryStringParams['limit']) {
                                        $intLimit = $arrQueryStringParams['limit'];
                                }

                                $arrUsers = $userDao->getUsers($intLimit);
                                $responseData = json_encode($arrUsers);
                        } catch (Error $e) {
                                $strErrorDesc = $e->getMessage() . 'Something went wrong! Please contact support.';
                                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
                        }
                } else {
                        $strErrorDesc = 'Method not supported';
                        $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
                }

                // send output
                if (!$strErrorDesc) {
                        $this->sendOutput(
                                $responseData,
                                array('Content-Type: application/json', 'HTTP/1.1 200 OK')
                        );
                } else {
                        $this->sendOutput(
                                json_encode(array('error' => $strErrorDesc)),
                                array('Content-Type: application/json', $strErrorHeader)
                        );
                }
        }

        public function editUser($id)
        {
                if (empty($_POST) && false !== strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
                        $content = file_get_contents('php://input');
                        $post = (array) json_decode($content, true);
                } else {
                        $post = $_POST;
                }
                if (is_string($id)) {
                        $id = intval($id);
                }
                $user = $this->userDao->getUserById($id);
                // 判断 $post 是否存在 password 字段，如果存在，则对密码进行加密
                if (isset($post['password'])) {
                        $post['password'] = password_hash($post['password'], PASSWORD_BCRYPT);
                }
                $user = array_merge($user, $post);
                // 转成UserModel对象
                $user = UserModel::fromArray($user);
                $this->userDao->updateUser($user);
                $this->success();
        }

        public function deleteUser($id)
        {
                if (is_string($id)) {
                        $id = intval($id);
                }
                $this->userDao->deleteUser($id);
                $this->success();
        }
}
